<template>
  <view v-if="icon">
    <!-- font字体图标 -->
    <text v-if="!!icon.cssClass" :class="[icon.cssClass, className]"></text>
    <template v-else-if="!!icon.imagePath">
      <!-- base64格式内容 -->
      <image
        v-if="isBase64Image(icon.imagePath)"
        :class="[className]"
        :src="icon.imagePath"
        alt=""
      />
      <!-- UTF-8 表情字符 -->
      <view
        v-else-if="isBase64(icon.imagePath)"
        :class="[className, ns.e('emoji')]"
      >
        {{ base64ToStr(icon.imagePath) }}
      </view>
      <!-- SVG 内容 -->
      <image
        v-else-if="isSvg(icon.imagePath)"
        :class="className"
        :src="handleSvg(icon.imagePath)"
      />
      <!-- 以svg结尾 -->
      <template v-else-if="icon.imagePath.endsWidth('svg')">
        <!-- 远程svg -->
        <image
          v-if="icon.imagePath.startsWith('http')"
          :class="className"
          :src="icon.imagePath"
          alt=""
        />
        <!-- 本地svg -->
        <image
          v-else
          :class="className"
          :src="BaseUrl + icon.imagePath"
          alt=""
        />
      </template>
      <!-- 远程图片 -->
      <image
        v-else-if="icon.imagePath.startsWith('http')"
        :class="className"
        :src="icon.imagePath"
        alt=""
      />
      <!-- 本地图片 -->
      <image v-else :class="className" :src="BaseUrl + icon.imagePath" alt="" />
    </template>
    <template v-else-if="icon.rawContent">
      <view
        v-if="isSvg(icon.rawContent)"
        :class="className"
        v-html="icon.rawContent"
      ></view>
      <image v-else :class="className" :src="icon.rawContent" alt="" />
    </template>
  </view>
</template>
<script lang="ts">
export default {
  options: {
    addGlobalClass: true,
    virtualHost: true,
    styleIsolation: "shared"
  }
}
</script>
<script lang="ts" setup>
import { useNamespace } from "@/use";
import { base64Encode } from "@/utils";
import { computed } from "vue";
import {
  base64ToStr,
  isBase64,
  isBase64Image,
  isSvg,
} from "@ibiz-template/core";
import { iconProps } from './i-biz-icon'

const props = defineProps(iconProps);

const BaseUrl = `${ibiz.env.assetsUrl}/${props.baseDir}/`;

const handleSvg = (str: string) => {
  const base64Svg = base64Encode(unescape(encodeURIComponent(str)));
  const imgUrl = `data:image/svg+xml;base64,${base64Svg}`;
  return imgUrl;
};

const ns = useNamespace("icon");
const className = computed(() => [ns.b()]);
</script>
<style lang="scss">
@include b(icon) {
  display: inline-block;
  width: 100%;
  height: 100%;
  ::v-deep {
    svg,
    svg.icon {
      width: 100%;
      height: 100%;
      path {
        fill: currentcolor;
      }
    }
  }
}
</style>
